from sqlalchemy import Column, Boolean, Integer, String, DateTime, Text, func
from sqlalchemy.orm import relationship

from app.core.database import Base


class User(Base):
    """用户模型 - 扩展基础用户模型以支持RBAC"""
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String(255), unique=True, index=True, nullable=False)
    username = Column(String(50), unique=True, index=True, nullable=False)
    hashed_password = Column(String(255), nullable=False)
    full_name = Column(String(100))
    avatar = Column(String(500))
    phone = Column(String(20))
    
    # 状态字段
    is_active = Column(Boolean, default=True, nullable=False)
    is_verified = Column(Boolean, default=False, nullable=False)
    is_superuser = Column(Boolean, default=False, nullable=False)
    
    # 审计字段
    last_login_at = Column(DateTime(timezone=True))
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 扩展信息
    extra_data = Column(Text)
    
    # 关联关系
    user_roles = relationship("UserRole", back_populates="user", cascade="all, delete-orphan")
    roles = relationship("Role", secondary="user_roles", back_populates="users", overlaps="user_roles")
    conversations = relationship("ChatConversation", back_populates="user", cascade="all, delete-orphan")
    crawler_jobs = relationship("CrawlerJob", back_populates="user", cascade="all, delete-orphan")
    scheduled_crawler_tasks = relationship("ScheduledCrawlerTask", back_populates="user", cascade="all, delete-orphan")
    
    sent_emails = relationship("EmailMessage", foreign_keys="EmailMessage.sender_id", back_populates="sender", lazy="dynamic")
    received_emails = relationship("EmailMessage", foreign_keys="EmailMessage.recipient_id", back_populates="recipient", lazy="dynamic")
    
    def __repr__(self):
        return f"<User(id={self.id}, email='{self.email}', username='{self.username}')>"
    
    def has_permission(self, permission_name: str) -> bool:
        """检查用户是否具有特定权限"""
        if self.is_superuser:
            return True
            
        for role in self.roles:
            if role.is_active:
                for permission in role.permissions:
                    if permission.name == permission_name and permission.is_active:
                        return True
        return False
    
    def has_role(self, role_name: str) -> bool:
        """检查用户是否具有特定角色"""
        return any(role.name == role_name and role.is_active for role in self.roles)
    
    def get_all_permissions(self):
        """获取用户的所有权限"""
        if self.is_superuser:
            return ["*"]  # 超级用户拥有所有权限
            
        permissions = set()
        for role in self.roles:
            if role.is_active:
                for permission in role.permissions:
                    if permission.is_active:
                        permissions.add(permission.name)
        return list(permissions)